package com.cjl.jvm.up;

public class SimpleHappenBefore {

    public static void main(String[] args) throws InterruptedException {

        for(int i=0;i<5000000;i++){
            SimpleHappenBefore.State state = new SimpleHappenBefore.State();
            ThreadA threadA=new ThreadA(state);
            ThreadB threadB=new ThreadB(state);
            threadA.start();
            threadB.start();

            threadA.join();
            threadB.join();
        }

        System.out.println("SimpleHappenBefore.main end");
    }

    static class ThreadA extends Thread{

        private final SimpleHappenBefore.State state;

        ThreadA(SimpleHappenBefore.State state) {
            this.state = state;
        }

        public void run(){
            state.a=1;
            state.b=1;
            state.c=1;
            state.d=1;
        }
    }

    static class ThreadB extends Thread{

        private final SimpleHappenBefore.State state;

        ThreadB(SimpleHappenBefore.State state) {
            this.state = state;
        }

        public void run(){
            if(state.b==1 && state.a==0){
                System.out.println("b=1,a=0");
            }

            if(state.c==1 && (state.b==0 || state.a == 0)){
                System.out.println("c=1,b or a = 0");
            }

            if(state.d==1 && (state.a==0 || state.b==0 || state.c==0)){
                System.out.println("d=1,a or b or c = 0");
            }
        }
    }


    //重排序的体现  偶尔输出  d=1,a or b or c = 0
    //volatile 写 线程中可见的共享变量刷入主内存     ,读 当前共享变量清除

    static class State {
        public int a = 0;
        public int b = 0;
        public int c = 0;
        public /*volatile*/ int d = 0;
    }
}


